const prompt = require('prompt');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const { version, getVersion } = require("./version/version");

prompt.start();

prompt.get(['输入当前版本说明'], async function (err, result) {
    if (err) {
        console.error('Error getting version description: ', err);
        return;
    }
    const versions=await version();
    const versionDescription = result['输入当前版本说明'];
    console.log(JSON.stringify(result));
    console.log('版本号：', versions);
    const currentVersionInfo = `## [${versions}] - ${new Date().toISOString().slice(0, 10)}\n### Updates\n- ${versionDescription}\n\n`;

    // 追加当前版本信息到全局版本更新日志
    const changelogPath = path.resolve(__dirname, 'ALL_VERSIONS_CHANGELOG.md');
    fs.appendFileSync(changelogPath, currentVersionInfo);

    console.log('Version Description Added: ' + versionDescription);

    // 调用 Webpack 打包
    exec('webpack --config webpack.config.prod.js --mode production', async (err, stdout, stderr) => {
        if (err) {
            console.error('Webpack build failed: ', err);
            return;
        }

        console.log('Webpack build succeeded');

        // 获取最新的全局版本更新日志
        const changelog = fs.readFileSync(changelogPath, 'utf8');


        // 保存更新的全局版本更新日志到dist目录和当前版本目录
        fs.writeFileSync(path.resolve(__dirname, './dist/ALL_VERSIONS_CHANGELOG.md'), changelog);
        const versionPath = path.resolve(__dirname, `./dist/${versions}`);
        if (!fs.existsSync(versionPath)) {
            fs.mkdirSync(versionPath, { recursive: true });
        }
        fs.writeFileSync(path.join(versionPath, 'ALL_VERSIONS_CHANGELOG.md'), changelog);

        console.log('All versions changelog updated.');
    });
});
